﻿Imports System.Text
Imports System.Text.RegularExpressions

Public Class Form1

    Private Function connect(ByVal url As String, ByVal user As String, ByVal password As String, ByVal remember As Boolean) As Boolean
        Dim vPost As Object
        Dim cSeparator As String = "&"
        Dim vHeaders As Object = "Content-Type: application/x-www-form-urlencoded" + Chr(10) + Chr(13)
        Dim cPostData As String = "username=" & user & cSeparator & "password=" & password & cSeparator & "remember=" & remember
        Try
            vPost = ASCIIEncoding.ASCII.GetBytes(cPostData)
            WebBrowser1.Navigate(url, Nothing, vPost, vHeaders)
            While (WebBrowser1.ReadyState <> SHDocVw.tagREADYSTATE.READYSTATE_COMPLETE)
                Application.DoEvents()
            End While
            connect = True
        Catch ex As Exception
            MsgBox(ex.Message)
            connect = False
        End Try
    End Function

    Private Function getSMSPage() As HtmlDocument
        Try
            WebBrowser1.Navigate("https://mip.sunrise.ch/mip/dyn/sms/sms")
            While (WebBrowser1.ReadyState <> SHDocVw.tagREADYSTATE.READYSTATE_COMPLETE)
                Application.DoEvents()
            End While
            Dim doc As HtmlDocument
            doc = WebBrowser1.Document
            getSMSPage = doc
        Catch ex As Exception
            MsgBox(ex.Message)
            getSMSPage = Nothing
        End Try
    End Function

    Private Function getRegex(ByVal strText As String, ByVal strPattern As String) As List(Of String)
        Dim list As New List(Of String)
        Dim myMatches As MatchCollection
        Dim myRegex As New Regex(strPattern)

        myMatches = myRegex.Matches(strText)
        ' Search for all the words in a string
        Dim successfulMatch As Match
        For Each successfulMatch In myMatches
            list.Add(successfulMatch.Value)
        Next
        getRegex = list
    End Function


    Private Function cleanHTMLTags(ByVal strText As String) As String
        Dim str As String

        str = strText

        str = Regex.Replace(str, "<script[^>]*>[\s\S]*?</script>", "")
        str = Regex.Replace(str, "<SCRIPT[^>]*>[\s\S]*?</SCRIPT>", "")
        str = Regex.Replace(str, "<style[^>]*>[\s\S]*?</style>", "")
        str = Regex.Replace(str, "<STYLE[^>]*>[\s\S]*?</STYLE>", "")
        str = Regex.Replace(str, "<HEAD[^>]*>[\s\S]*?</HEAD>", "")
        str = Regex.Replace(str, "<head[^>]*>[\s\S]*?</head>", "")
        str = Regex.Replace(str, Chr(10), "")
        str = Regex.Replace(strText, Chr(13), "").Trim

        cleanHTMLTags = str
    End Function

    Private Function getExpediteur(ByVal GetHTML As String)
        Dim strExpe As String = ""
        For Each s As String In getRegex(GetHTML, "<TR>[^>]*>[\s\S]*?</TR>")
            If s.Contains("Expéditeur") Then

                strExpe = Regex.Replace(s, "</TR>", "")
                strExpe = Regex.Replace(strExpe, "<TR>", "")
                strExpe = Regex.Replace(strExpe, "</TD>", "")
                strExpe = Regex.Replace(strExpe, "<TD.*>", "")
                strExpe = Regex.Replace(strExpe, "Expéditeur", "")
                strExpe = Regex.Replace(strExpe, Chr(10), "")
                strExpe = Regex.Replace(strExpe, Chr(13), "").Trim

            End If
        Next
        getExpediteur = strExpe
    End Function

    Private Function getMessagesRestant(ByVal GetHTML As String) As Integer
        Dim strExpe As String = ""
        For Each s As String In getRegex(GetHTML, "<TD>[^>]*>[\s\S]*?</TD>")
            If s.Contains("Gratuits") Then
                strExpe = Regex.Replace(s, "</TD>", "")
                strExpe = Regex.Replace(strExpe, "<TD>", "")
                strExpe = strExpe.Split("<BR>")(0)
                strExpe = Regex.Replace(strExpe, "Gratuits", "").Trim()
            End If
        Next
        getMessagesRestant = strExpe
    End Function

    Private Function getContactId(ByVal strBloc As String) As String
        Dim id As String = ""

        For Each s As String In getRegex(strBloc, "<INPUT.*contactId")
            For Each t As String In getRegex(s, "value=.*name")
                t = Regex.Replace(t, "value=", "")
                t = Regex.Replace(t, "name", "")
                t = t.Trim
                id = t
            Next
        Next
        getContactId = id
    End Function

    Private Function getContactNum(ByVal strBloc As String) As String
        Dim num As String = ""
        For Each s As String In getRegex(strBloc, "<DIV class=contact style.*>[^>]*>[\s\S]*?</DIV>")
            Dim t(2) As String
            s = s.Replace("</DIV>", "")
            s = s.Substring(s.LastIndexOf(">") + 1)
            t = s.Split(",")
            num = t(1)
        Next
        getContactNum = num
    End Function

    Private Function getContactNom(ByVal strBloc As String) As String
        Dim nom As String = ""
        For Each s As String In getRegex(strBloc, "<DIV class=contact style.*>[^>]*>[\s\S]*?</DIV>")
            Dim t(2) As String
            s = s.Replace("</DIV>", "")
            s = s.Substring(s.LastIndexOf(">") + 1)
            t = s.Split(",")
            nom = t(0)
        Next
        getContactNom = nom
    End Function

    Private Function getContacts(ByVal GetHTML As String) As List(Of String())
        Dim liste As New List(Of String())

        For Each s As String In getRegex(GetHTML, "<DIV class=contact style.*>[^>]*>[\s\S]*?contactId")
            Dim t(3) As String
            t(0) = getContactNom(s)
            t(1) = getContactNum(s)
            t(2) = getContactId(s)
            liste.Add(t)
        Next
        getContacts = liste
    End Function

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim docSMSPage As HtmlDocument

        If (connect("https://mip.sunrise.ch/mip/dyn/login/login?SAMLRequest=fVJdT8IwFH038T80fd8XRmMaNoMSIgnqAtMH30p3xxrWdvZ2oP%2FeMkDwQR97eno%2Bbu%2Fw7lM1ZAMWpdEpTcKYEtDClFKvUvpaTIJbepddXgyRq6Zlo87Veg4fHaAj%2FqVG1l%2BktLOaGY4SmeYKkDnBFqOnGRuEMWutcUaYhpLpOKV1K9YrzWspYF1LKZcVrFuhlhIqgHVVgQJelVxR8naMNdjFmiJ2MNXouHYeiuPbIBkEyU2RJOw6ZoOrd0ryg9O91PsG%2F8Va7knIHosiD%2FKXRdELbGQJ9tmzU7oyZtVAKIza2eccUW487GwHlIwQwTqf78Fo7BTYBdiNL%2FU6n%2FmSzrXIomi73YYnlYhH2Gkr0Z%2FqiAukWT9Y1nezZxP9Pzk%2FWtPsJD6MzqSyw4ftekzHuWmk%2BCKjpjHbBwvc%2FZSYGKu4%2B9stCZMekWVQ9VTWaWxByEpCSUmU7V1%2Fb4bfl28%3D&amp;RelayState=https%3A%2F%2Fwww.google.com%2Fa%2Fsunrise.ch%2FServiceLogin%3Fcontinue%3Dhttp%253A%252F%252Fpartnerpage.google.com%252Fsunrise.ch%252Fdefault%252Fpostlogin%253Fpid%253Dsunrise.ch%2526url%253Dhttp%253A%252F%252Fpartnerpage.google.com%252Fsunrise.ch%26followup%3Dhttp%253A%252F%252Fpartnerpage.google.com%252Fsunrise.ch%252Fdefault%252Fpostlogin%253Fpid%253Dsunrise.ch%2526url%253Dhttp%253A%252F%252Fpartnerpage.google.com%252Fsunrise.ch%26service%3Dig%26passive%3Dtrue%26cd%3DUS%26hl%3Dfr%26nui%3D1%26ltmpl%3Ddefault%26go%3Dtrue%26passive_sso%3Dtrue", "himpensa@sunrise.ch", "tounu33_", False)) Then
            docSMSPage = getSMSPage()

            Dim GetHTML As String = docSMSPage.All(0).OuterHtml
            GetHTML = cleanHTMLTags(GetHTML)

            Label1.Text = getExpediteur(GetHTML)
            Label2.Text = getMessagesRestant(GetHTML) & "/100"


           
            lvDest.Columns.Add("Nom", 80)
            lvDest.Columns.Add("Numero", 80)

            loadContacts(GetHTML)
            
        Else
            MsgBox("Error : Unable to connect, check you can reach the network with your usual browser, check your user name, password, ...")
        End If

    End Sub

    Private Sub loadContacts(ByVal GetHTML As String)
        lvContacts.Clear()
        lvContacts.Columns.Add("Nom", 170)
        lvContacts.Columns.Add("Numero", 110)
        For Each cont As String() In getContacts(GetHTML)
            Dim itm As New ListViewItem(cont)
            lvContacts.Items.Add(itm)
        Next

    End Sub
    Private Sub lvContacts_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lvContacts.DoubleClick
        Dim contact(3) As String
        contact(0) = lvContacts.SelectedItems.Item(0).SubItems(0).Text
        contact(1) = lvContacts.SelectedItems.Item(0).SubItems(1).Text
        contact(2) = lvContacts.SelectedItems.Item(0).SubItems(2).Text
        lvContacts.SelectedItems.Item(0).Remove()
        Dim itm As New ListViewItem(contact)
        lvDest.Items.Add(itm)
    End Sub

    Private Sub lvDest_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lvDest.DoubleClick
        Dim contact(3) As String
        contact(0) = lvDest.SelectedItems.Item(0).SubItems(0).Text
        contact(1) = lvDest.SelectedItems.Item(0).SubItems(1).Text
        contact(2) = lvDest.SelectedItems.Item(0).SubItems(2).Text
        lvDest.SelectedItems.Item(0).Remove()
        Dim itm As New ListViewItem(contact)
        lvContacts.Items.Add(itm)
    End Sub



    Private Sub ContextMenuContacts_Opening(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles ContextMenuContacts.Opening
        If lvContacts.SelectedItems.Count = 0 Then
            RemoveContactToolStripMenuItem.Enabled = False
        Else
            RemoveContactToolStripMenuItem.Enabled = True
        End If
    End Sub



    Private Sub RemoveContactToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RemoveContactToolStripMenuItem.Click
        If MsgBox("Etes vous sur de vouloir supprimer " + lvContacts.SelectedItems.Item(0).SubItems(0).Text + " de la liste de vos contacts", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
            deleteContact(lvContacts.SelectedItems.Item(0).SubItems(2).Text)
            lvContacts.SelectedItems.Item(0).Remove()
            MsgBox("Contact supprimé")
        End If


    End Sub

    Private Function deleteContact(ByVal id As String) As Boolean
        Dim url As String = "https://mip.sunrise.ch/mip/dyn/sms/sms?up_contactsPerPage=6&lang=fr&country=us&.lang=fr&.country=us&synd=ig&mid=14&ifpctok=-9089929195439787933&parent=http://partnerpage.google.com&libs=xB-WoatiXJY/lib/libcore.js,4aEaFcUuV9I/lib/libdynamic-height.js&extern_js=/extern_js/f/CgJlbhICdXMrMBA4ACw/gCQhJE1wsLw.js"
        Dim vPost As Object
        Dim cSeparator As String = "&"
        Dim vHeaders As Object = "Content-Type: application/x-www-form-urlencoded" + Chr(10) + Chr(13)
        Dim cPostData As String = "contactId=" & id & cSeparator & "del=supprimer" & cSeparator & "task=delContact"
        Try
            vPost = ASCIIEncoding.ASCII.GetBytes(cPostData)
            WebBrowser1.Navigate(url, Nothing, vPost, vHeaders)
            While (WebBrowser1.ReadyState <> SHDocVw.tagREADYSTATE.READYSTATE_COMPLETE)
                Application.DoEvents()
            End While
            deleteContact = True
        Catch ex As Exception
            MsgBox(ex.Message)
            deleteContact = False
        End Try
    End Function

    Private Function createContact(ByVal nom As String, ByVal num As String) As Boolean
        Dim url As String = "https://mip.sunrise.ch/mip/dyn/sms/sms?up_contactsPerPage=6&lang=fr&country=us&.lang=fr&.country=us&synd=ig&mid=14&ifpctok=-9089929195439787933&parent=http://partnerpage.google.com&libs=xB-WoatiXJY/lib/libcore.js,4aEaFcUuV9I/lib/libdynamic-height.js&extern_js=/extern_js/f/CgJlbhICdXMrMBA4ACw/gCQhJE1wsLw.js"
        Dim vPost As Object
        Dim cSeparator As String = "&"
        Dim vHeaders As Object = "Content-Type: application/x-www-form-urlencoded" + Chr(10) + Chr(13)
        Dim cPostData As String = "contact=" & nom & ", " & num & cSeparator & "task=addContact"
        Try
            vPost = ASCIIEncoding.ASCII.GetBytes(cPostData)
            WebBrowser1.Navigate(url, Nothing, vPost, vHeaders)
            While (WebBrowser1.ReadyState <> SHDocVw.tagREADYSTATE.READYSTATE_COMPLETE)
                Application.DoEvents()
            End While
            createContact = True
        Catch ex As Exception
            MsgBox(ex.Message)
            createContact = False
        End Try
    End Function

    Private Sub AddNewContactToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddNewContactToolStripMenuItem.Click
        Dim nom As String = ""
        Dim num As String = ""
        nom = InputBox("Saisir le nom du contact")
        num = InputBox("Saisir le numéro du contact au format internationnal en débutant par l'indicatif de votre pays (ex: 00336xxxxxxxx pour un portable français")
        If createContact(nom, num) Then
            Dim GetHTML As String = getSMSPage().All(0).OuterHtml
            loadContacts(GetHTML)
            MsgBox(nom & " ajouté")
        End If
    End Sub

    Private Sub SelectAllContactsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SelectAllContactsToolStripMenuItem.Click
        For Each lv As ListViewItem In lvContacts.Items
            lvContacts.Items(0).Selected = True
            lvContacts.Select()
            Dim contact(3) As String
            contact(0) = lvContacts.SelectedItems.Item(0).SubItems(0).Text
            contact(1) = lvContacts.SelectedItems.Item(0).SubItems(1).Text
            contact(2) = lvContacts.SelectedItems.Item(0).SubItems(2).Text
            lvContacts.SelectedItems.Item(0).Remove()
            Dim itm As New ListViewItem(contact)
            lvDest.Items.Add(itm)
        Next
    End Sub

    Private Sub btEnvoyer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btEnvoyer.Click
        For Each lv As ListViewItem In lvDest.Items
            lvDest.Items(0).Selected = True
            lvDest.Select()
            Dim contact(3) As String
            contact(0) = lvDest.SelectedItems.Item(0).SubItems(0).Text
            contact(1) = lvDest.SelectedItems.Item(0).SubItems(1).Text
            contact(2) = lvDest.SelectedItems.Item(0).SubItems(2).Text
            lvDest.SelectedItems.Item(0).Remove()
            Dim itm As New ListViewItem(contact)
            lvContacts.Items.Add(itm)
            envoyerSMS(contact)
        Next
        MsgBox("Message envoyé")
    End Sub

    Public Function getCharsRestantSMS() As String
        Dim strTaille As String
        Dim strTmp As String
        strTmp = txtTexteMessage.Text
        strTaille = (160 - (strTmp.Length Mod 160) - 1).ToString + "/" + (((strTmp.Length \ 160) + 1) * 160).ToString
        getCharsRestantSMS = strTaille
    End Function

    Public Function getNbSMS() As String
        Dim strTaille As String
        Dim strTmp As String
        strTmp = txtTexteMessage.Text
        strTaille = (((strTmp.Length \ 160) + 1) * lvDest.Items.Count).ToString
        getNbSMS = strTaille
    End Function


    Public Function getTailleSMS() As String
        Dim strTaille As String
        Dim strTmp As String
        strTmp = txtTexteMessage.Text
        strTaille = (160 - (strTmp.Length Mod 160) - 1).ToString + " / " + ((strTmp.Length \ 160) + 1).ToString
        getTailleSMS = strTaille
    End Function
    Public Function getContentSMS() As String
        getContentSMS = txtTexteMessage.Text
    End Function

    Private Function envoyerSMS(ByVal contact As String()) As Boolean
        Dim url As String = "https://mip.sunrise.ch/mip/dyn/sms/sms?up_contactsPerPage=6&lang=fr&country=us&.lang=fr&.country=us&synd=ig&mid=14&ifpctok=-9089929195439787933&parent=http://partnerpage.google.com&libs=xB-WoatiXJY/lib/libcore.js,4aEaFcUuV9I/lib/libdynamic-height.js&extern_js=/extern_js/f/CgJlbhICdXMrMBA4ACw/gCQhJE1wsLw.js"
        Dim vPost As Object
        Dim cSeparator As String = "&"
        Dim vHeaders As Object = "Content-Type: application/x-www-form-urlencoded" + Chr(10) + Chr(13)
        Dim cPostData As String = "recipient=" & contact(1) & cSeparator & "type=SMS" & cSeparator & "charsLeft=" & getTailleSMS() & cSeparator & "message=" & getContentSMS()
        Try
            vPost = ASCIIEncoding.ASCII.GetBytes(cPostData)
            WebBrowser1.Navigate(url, Nothing, vPost, vHeaders)
            While (WebBrowser1.ReadyState <> SHDocVw.tagREADYSTATE.READYSTATE_COMPLETE)
                Application.DoEvents()
            End While
            envoyerSMS = True
        Catch ex As Exception
            MsgBox(ex.Message)
            envoyerSMS = False
        End Try
    End Function

    Private Sub txtTexteMessage_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtTexteMessage.KeyDown
        lblChars.Text = getCharsRestantSMS()
        lblNbSMS.Text = getNbSMS()
    End Sub


End Class
